import config from '../config.js';
import uploader from './s3uploader.js';
import path from 'path';
import fs from 'fs';

function s3UploadMiddleware(fieldName, fileFormName = 'file') {
    return function (req, res, next) {
        let uploadField = fieldName || req.params.fieldname;
        const uploadSettings = config.upload[uploadField];
        if (!uploadSettings) {
            return res.badRequest(`No upload settings found for ${uploadField}`);
        }

        // 确保临时目录存在
        const tempDir = path.resolve(process.cwd(), 'uploads/temp');
        if (!fs.existsSync(tempDir)) {
            fs.mkdirSync(tempDir, { recursive: true });
            console.log(`创建临时目录: ${tempDir}`);
        }

        // 确保上传目录存在
        const uploadDir = uploadSettings.uploadDir;
        if (uploadDir) {
            const absoluteUploadDir = path.resolve(process.cwd(), uploadDir);
            if (!fs.existsSync(absoluteUploadDir)) {
                fs.mkdirSync(absoluteUploadDir, { recursive: true });
                console.log(`创建上传目录: ${absoluteUploadDir}`);
            }
        }

        uploader.upload(uploadField, fileFormName).array(fileFormName)(req, res, (err) => {
            if(err){
                console.error('文件上传错误:', err);
                return res.badRequest(err.message);
            }
            return next();
        });
    };
}

export { s3UploadMiddleware };